/**
 * 
 */
package com.comp6231.replica2;

import java.util.Hashtable;

import com.comp6231.common.Request;
import com.comp6231.coordinator.Coordinator;
import com.comp6231.replica2.server.StationServer;

/**
 * @author Farzana Alam
 * 
 */
public class CoordinatorReplica2 extends Coordinator {

	public CoordinatorReplica2(String hostName, String UDPPort,
			String controlUDPPort, String replicaName, int replicaID,
			Hashtable<String, String[]> coordinatorReplicaList,
			Hashtable<String, String[]> frontEndList) {

		super(hostName, UDPPort, controlUDPPort, replicaName, replicaID,
				coordinatorReplicaList, frontEndList);
		new Thread(new StationServer()).start();
	}

	@Override
	public String invokeMethod(Request request) {
		RequestParser reqParser = new RequestParser(request.getOperation(),
				request.getOperationArguments());

		return callLocalServerMethod(request, reqParser, request.getOperation());

	}

	private String callLocalServerMethod(Request request,
			RequestParser reqParser, String operation) {
		CorbaClient localServerCall = CorbaClient.getCORBAClient(reqParser
				.getBadgeID());

		StringBuilder result = new StringBuilder();
		String locallyProcessedResult = "Success";
		String replyFromServer = "";

		switch (operation.trim().toUpperCase()) {
		case "CREATEMRECORD":
			// Expected: "Success"/"Fail"
			replyFromServer = localServerCall.createMRecord(
					reqParser.getFirstName(), reqParser.getLastName(),
					reqParser.getAddress(), reqParser.getLastDate(),
					reqParser.getLastLocation(), reqParser.getStatus());
			break;
		case "CREATECRECORD":
			// Expected: "Success"/"Fail"
			replyFromServer = localServerCall.createCRecord(
					reqParser.getFirstName(), reqParser.getLastName(),
					reqParser.getDescription(), reqParser.getStatus());
			break;
		case "GETRECORDCOUNTS":
			// Expected eg. "SPVM: 8, SPB: 9, SPL: 7"
			replyFromServer = localServerCall.getRecordCounts();
			break;
		case "EDITRECORD":
			// Expected: "Success"/"Fail"
			replyFromServer = localServerCall.editCRecord(
					reqParser.getLastName(), reqParser.getRecordID(),
					reqParser.getStatus());

			break;
		case "TRANSFERRECORD":
			// Expected: "Success"/"Fail"
			replyFromServer = localServerCall.transferRecord(
					reqParser.getRecordID(),
					reqParser.getRemoteStationServerName());
			break;
		default:
			locallyProcessedResult = "Fail";
		}

		if (replyFromServer.equals("")) {
			locallyProcessedResult = "Fail";
		}

		result.append(locallyProcessedResult + " ## ").append(replyFromServer);

		if (locallyProcessedResult.equalsIgnoreCase("Success")) {
			System.out
					.println(request.getRequestID() + " is processed locally");
			request.setLocallyProcessed(true);
		}

		return result.toString();
	}
}
